﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Management;
using System.Web.Mvc;
using DataMongo.Entities;
using ChatJs.Net;
using DataMongo;
using HtmlAgilityPack;
using Microsoft.Ajax.Utilities;
using MongoDB.Bson.IO;
using MVCMongo.Code;
using MVCMongo.Code.LongPolling.Chat;
using MVCMongo.Code.SignalR;
using DataMongo.Entities;
using MVCMongo.Services;
using MVCMongo.ViewModel;
using WebMatrix.WebData;

namespace MVCMongo.Controllers
{
    [Authorize]
    public class ProfileController : Controller
    {
        private int userId = WebSecurity.GetUserId(WebSecurity.CurrentUserName);
        //
        // GET: /Profile/

        public ActionResult Index()
        {

            var existingUser = ChatHelper.GetChatUserFromCookie(this.Request);
            var connection = new RepositoryBaseMongo("Status");
            var data = connection.GetAll<Status>().Where(x => !x.IsDeleted).OrderByDescending(x => x.CreatedDate);
            var viewModel = new ProfileIndexViewModel();
            viewModel.Statuses = data;
            viewModel.ChatModel = null;
            viewModel.PostType = "1";
            if (ChatHub.IsEmailInChatUser(WebSecurity.CurrentUserName))
            {
                viewModel.ChatModel = new ChatViewModel()
                {
                    IsUserAuthenticated = true,
                    UserId = userId,
                    UserName = WebSecurity.CurrentUserName,
                    UserProfilePictureUrl = "/content/UserProfile/User/" + UtilityService.GetUserImageByUserName(WebSecurity.CurrentUserName)
                };

                return View(viewModel);

            } else if (existingUser != null)
            {
                if (!ChatHub.IsUserRegistered(existingUser))
                {
                    // cookie is invalid
                    ChatHelper.RemoveCookie(this.Response);
                   
                    return this.RedirectToAction("Index");
                }

                viewModel.ChatModel = new ChatViewModel()
                {
                    IsUserAuthenticated = true,
                    UserId = userId,
                    UserName = WebSecurity.CurrentUserName,
                    UserProfilePictureUrl = "/content/UserProfile/User/" + UtilityService.GetUserImageByUserName(WebSecurity.CurrentUserName)
                };

                return View(viewModel);

            }
            
            var user = new ChatUser()
            {
                Name = UtilityService.GetCurrentUserFullName(WebSecurity.CurrentUserId),
                Email = WebSecurity.CurrentUserName,
                ProfilePictureUrl ="/content/UserProfile/User/" + UtilityService.GetCurrentUserImage(WebSecurity.CurrentUserId),
                Id = new Random().Next(100000),
                Status = ChatUser.StatusType.Online,
                RoomId = ChatController.ROOM_ID_STUB
            };

            // for signalr
            {
                ChatHub.RegisterNewUser(user);
            }

            // for long-polling
            {
                ChatServer.SetupRoomIfNonexisting(ChatController.ROOM_ID_STUB);
                ChatServer.Rooms[ChatController.ROOM_ID_STUB].RegisterNewUser(user);
            }
            ChatHelper.CreateNewUserCookie(this.Response, user);
                // in this case the authentication cookie is valid and we must render the chat
                 viewModel.ChatModel = new ChatViewModel()
                {
                    IsUserAuthenticated = true,
                    UserId = userId,
                    UserName = WebSecurity.CurrentUserName,
                    UserProfilePictureUrl = "/content/UserProfile/User/" + UtilityService.GetUserImageByUserName(WebSecurity.CurrentUserName)
                };
            
            return View(viewModel);
        }
        public ActionResult Search(string search)
        {
            var connection = new RepositoryBaseMongo("Users");
            var conF = new RepositoryBaseMongo("FriendList");
            
            var data = connection.GetAll<Users>().ToList().Where(x=>x.UserId != userId);
            var friendList = conF.GetAll<FriendList>().ToList();
            if (friendList.Any())
            {
                var frendId = friendList.Select(x => x.FriendId).ToList();
                var myId = friendList.Select(x => x.MyId).ToList();
                data = data.Where(x => !frendId.Contains(x.UserId) && !myId.Contains(x.UserId));
              
            }
          
            var result = data.Where(x => x.FirstName.ToLower().Contains(search.ToLower())|| x.LastName.ToLower().Contains(search.ToLower())).ToList();
            return View(result);
        }

        public ActionResult FriendRequest(int id)
        {
            var connection = new RepositoryBaseMongo("FriendRequest");
            var userlist = connection.GetAll<FriendRequest>().ToList();
            int Id = 0;
            if (userlist.Any())
                Id = userlist.Max(x => x.FriendRequestId);
            Id += 1;
            var friendR = new FriendRequest();
            friendR.RequestDate= DateTime.UtcNow;
            friendR.SenderId = userId;
            friendR.ReceiverId = id;
            friendR.FriendRequestId = Id;
            connection.InsertOrUpdate(friendR);
            return RedirectToAction("Index");


        }

        public ActionResult Notification()
        {
            
            var data = UtilityService.FriendRequestList(userId);

            return PartialView("_partialNotification", data);
            // var partialNotification = this.RenderPartialViewToString("_partialNotification", data);
            // return Json(partialNotification , JsonRequestBehavior.AllowGet);
        }
        public ActionResult NotificationOff(int friendRId, string type)
        {
            var connection = new RepositoryBaseMongo("FriendRequest");

            var  list = (from f in connection.GetAll<FriendRequest>()
                         where f.FriendRequestId == friendRId 
                                select f).ToList();
            if (list.Any())
            {
                // Update Friend Request
                var restult = list.FirstOrDefault();
                restult.IsRead = true;
                connection.InsertOrUpdate(restult);

                // Adding in Friend List
                 if (type =="c")
            {
                var conF = new RepositoryBaseMongo("FriendList");
                var friendList = conF.GetAll<FriendList>().ToList();
                  int IdC = 0;
                  if (friendList.Any())
                      IdC = friendList.Max(x => x.FriendListId);
                  IdC += 1;
                var friendListObj = new FriendList();
                friendListObj.FriendListId = IdC;
                friendListObj.MyId = userId;
                friendListObj.FriendId = restult.SenderId;
                friendListObj.AccpetDate = DateTime.UtcNow;
                conF.InsertOrUpdate(friendListObj);

            }
                // Adding in UnFriend List
                if (type == "n")
                {
                    var conN = new RepositoryBaseMongo("UnFriendList");
                    var unfriendList = conN.GetAll<UnFriendList>().ToList();
                    int IdN = 0;
                    if (unfriendList.Any())
                        IdN = unfriendList.Max(x => x.UnFriendListId);
                    IdN += 1;
                    var unfriendListObj = new UnFriendList();
                    unfriendListObj.UnFriendListId = IdN;
                    unfriendListObj.MyId = userId;
                    unfriendListObj.FriendId = restult.SenderId;
                    unfriendListObj.UnAccpetDate = DateTime.UtcNow;
                    conN.InsertOrUpdate(unfriendListObj);
                }
            }
           
            return RedirectToAction("Index");


        }

        public ActionResult FriendList()
        {
            var connection = new RepositoryBaseMongo("FriendList");
            var list = connection.GetAll<FriendList>().Where(x => x.MyId == userId || x.FriendId == userId).Take(5);
            return PartialView(list);

        }
        [HttpPost]
        public ActionResult StatusPost(string post)
        {
            var conS = new RepositoryBaseMongo("Status");
            var statusList = conS.GetAll<Status>().ToList();
            int Id = 0;
            if (statusList.Any())
                Id = statusList.Max(x => x.StatusId);
            Id += 1;

            var status = new Status()
            {
                CreatedDate = DateTime.UtcNow,
                StatusId = Id,
                StatusText = post,
                UserId = userId
            };
            conS.InsertOrUpdate(status);
            return RedirectToAction("Index");

        }

        public ActionResult FriendInvite()
        {
            //  var connection = new RepositoryBaseMongo("Users");
            // var conF = new RepositoryBaseMongo("FriendList");
            ////double list for friends
            // var friendList = conF.GetAll<FriendList>().Where(x => x.MyId == userId).Select(x => x.FriendId).Distinct();
            // var secondlist = conF.GetAll<FriendList>().Where(x => x.FriendId == userId).Select(x => x.MyId).Distinct();
            // var data = connection.GetAll<Users>().ToList().Where(x => !friendList.Contains(x.UserId) || secondlist.Contains(x.UserId));

             var connection = new RepositoryBaseMongo("Users");
             var conF = new RepositoryBaseMongo("FriendList");

             var data = connection.GetAll<Users>().ToList().Where(x => x.UserId != userId);
             var friendList = conF.GetAll<FriendList>().ToList();
             if (friendList.Any())
             {
                 var frendId = friendList.Select(x => x.FriendId).ToList();
                 var myId = friendList.Select(x => x.MyId).ToList();
                 data = data.Where(x => !frendId.Contains(x.UserId) && !myId.Contains(x.UserId));

             }
             return View("Search", data);
        }
        public ActionResult FriendListAll()
        {
            var connection = new RepositoryBaseMongo("FriendList");
            var list = connection.GetAll<FriendList>().Where(x => x.MyId == userId || x.FriendId == userId);
            return View(list);

        }

        public ActionResult UserProfileEdit()
        {
            var connection = new RepositoryBaseMongo("Users");
            var connectionU = new RepositoryBaseMongo("UserDetails");
            var connectionF = new RepositoryBaseMongo("FriendList");
            var conA = new RepositoryBaseMongo("Album");
            
            var user = connection.GetAll<Users>().FirstOrDefault(x => x.UserId == userId);
            var userDetails = connectionU.GetAll<UserDetails>().FirstOrDefault(x => x.UserId == userId);
            var viewModel = new UserProfileViewModel();
            viewModel.Albums = conA.GetAll<Album>().Where(x => x.UserId == userId);
            viewModel.Users = user;
            viewModel.UserDetails = userDetails;

            viewModel.UserFriendList = (from n in UtilityService.GetFriendList()
                                        join u in connection.GetAll<Users>().ToList() on n equals u.UserId
                                        select new User_Friend()
                                        {
                                            UserId = u.UserId,
                                            FullName = u.FirstName + " " + u.LastName,
                                            ImageUrl = u.ImageUrl
                                        }).ToList();

            // BirthDay
            var doblist = user.BirthDay.ToShortDateString().Split('/');
            ViewBag.Month = doblist[0];
            ViewBag.day = doblist[1];
            ViewBag.Year = doblist[2];

            var conSexOr = new RepositoryBaseMongo("SexualOrientation");
            viewModel.SexOrientationList = new SelectList(conSexOr.GetAll<SexualOrientation>(), "SOId", "Title");
            var conEn = new RepositoryBaseMongo("Ethnicity");
            viewModel.EthnicityList = new SelectList(conEn.GetAll<Ethnicity>(), "EthnicityId", "Title");
            var conHeAndWe = new RepositoryBaseMongo("HeightWeight");
            viewModel.HeightList = new SelectList(conHeAndWe.GetAll<HeightWeight>().Where(x => x.Type == "Height"), "HeightWeightId", "Title");
            viewModel.WeightList = new SelectList(conHeAndWe.GetAll<HeightWeight>().Where(x => x.Type == "Weight"), "HeightWeightId", "Title");
            var conBloodType = new RepositoryBaseMongo("BodyType");
            viewModel.BloodTypeList = new SelectList(conBloodType.GetAll<BodyType>(), "BodyTypeId", "Title");
            var conReg = new RepositoryBaseMongo("Religion");
            viewModel.RegilionList = new SelectList(conReg.GetAll<Religion>(), "ReligionId", "Title");
            var conCon = new RepositoryBaseMongo("Country");
            viewModel.CountryList = new SelectList(conCon.GetAll<Country>(), "CountryID", "Title");
            var conState = new RepositoryBaseMongo("State");
            viewModel.StateList = new SelectList(conState.GetAll<State>(), "StateId", "Title");
            var conSocial = new RepositoryBaseMongo("SocialSetting");
            var conUserSocial = new RepositoryBaseMongo("UserSocialSetting");
            viewModel.SocialSettingList =
                conSocial.GetAll<SocialSetting>()
                    .Select(x => new User_Social()
                    {
                        Title = x.Title,
                        SocialId = x.SocialSettingId,
                        IsCheck = conUserSocial.GetAll<UserSocialSetting>().Any(y => y.SocialSettingId == x.SocialSettingId) ? true : false

                    })
                    .ToList();
            var conTvHabit = new RepositoryBaseMongo("TVHabit");
            var conUserTv = new RepositoryBaseMongo("UserTvHabit");
            var test = conUserTv.GetAll<UserTvHabit>().Any(y => y.IvHabitId == 1);
            viewModel.TvHabitList =
                conTvHabit.GetAll<TVHabit>()
                    .Select(x => new User_TVList()
                    {
                        Title = x.Title,
                        TvHabitId = x.TVHabitId,
                        IsCheck = conUserTv.GetAll<UserTvHabit>().Any(y => y.IvHabitId == x.TVHabitId) ? true : false

                    })
                    .ToList();



            viewModel.DegreeList = new SelectList(Enum.GetValues(typeof(DegreeEnum)).Cast<DegreeEnum>().Select(x => new SelectListItem()
            {
                Text = (x).ToString(),
                Value = ((int)x).ToString()
            }), "Value", "Text");


            viewModel.CityList = new SelectList(Enum.GetValues(typeof(CityEnum)).Cast<CityEnum>().Select(x => new SelectListItem()
            {
                Text = (x).ToString(),
                Value = ((int)x).ToString()
            }), "Value", "Text");

            viewModel.HabitList = new SelectList(Enum.GetValues(typeof(HabitualEnum)).Cast<HabitualEnum>().Select(x => new SelectListItem()
            {
                Text = (x).ToString(),
                Value = ((int)x).ToString()
            }), "Value", "Text");
            viewModel.EyeColorList = new SelectList(Enum.GetValues(typeof(EyeColorEnum)).Cast<EyeColorEnum>().Select(x => new SelectListItem()
            {
                Text = (x).ToString(),
                Value = ((int)x).ToString()
            }), "Value", "Text");

            viewModel.LivingList = new SelectList(Enum.GetValues(typeof(LivingEnum)).Cast<LivingEnum>().Select(x => new SelectListItem()
            {
                Text = (x).ToString(),
                Value = ((int)x).ToString()
            }), "Value", "Text");

            var connectionUP = new RepositoryBaseMongo("UserPortfolio");
            viewModel.UserPortfolios = connectionUP.GetAll<UserPortfolio>().Where(x => x.UserId == userId).ToList();
            var connectionUS = new RepositoryBaseMongo("UserSkill");
            viewModel.UserSkills = connectionUS.GetAll<UserSkill>().Where(x => x.UserId == userId).ToList();
            var connectionUA = new RepositoryBaseMongo("UserAcademyInfo");
            viewModel.UserAcademyInfos = connectionUA.GetAll<UserAcademyInfo>().Where(x => x.UserId == userId).ToList();
            var connectionUC = new RepositoryBaseMongo("UserCompanyInfo");
            viewModel.UserCompanyInfos = connectionUC.GetAll<UserCompanyInfo>().Where(x => x.UserId == userId).ToList();
          viewModel.YearList= new List<int>();
            var currentYear = DateTime.UtcNow.Year;
            for (int i = DateTime.UtcNow.AddYears(-80).Year; i <= currentYear; i++)
            {
                viewModel.YearList.Add(i);
            }
          
           
            

            return View(viewModel);
        }

         [HttpPost]
        public ActionResult UserProfileAcademyInfo(UserAcademyInfo model )
         {
            
             var connectionU = new RepositoryBaseMongo("UserAcademyInfo");
             if (model.UserAcademyInfoId == 0)
             {
                 var statusList = connectionU.GetAll<UserAcademyInfo>().ToList();
                 int Id = 0;
                 if (statusList.Any())
                     Id = statusList.Max(x => x.UserAcademyInfoId);
                 Id += 1;

                 model.UserId = userId;
                 model.UserAcademyInfoId = Id;
                 connectionU.InsertOrUpdate(model);


             }
             else
             {

                 var academy = connectionU.GetAll<UserAcademyInfo>().FirstOrDefault(x => x.UserAcademyInfoId == model.UserAcademyInfoId);
                 academy.ScCountryId= model.ScCountryId;
                     academy.ScState= model.ScState;
                     academy.ScCity= model.ScCity;
                     academy.ScType= model.ScType;
                     academy.ScStartDate= model.ScStartDate;
                     academy.ScEndDate= model.ScEndDate;
                     academy.ScDegreeId= model.ScDegreeId;
                     academy.Description= model.Description;
                 academy.ScName = model.ScName;
                     academy.Status= model.Status;

                     connectionU.InsertOrUpdate(academy);
     

             }

            
             
             return RedirectToAction("UserProfileEdit");
         }

       
            
         [HttpPost]
         public ActionResult UserProfileSkillInfo(UserSkill model)
         {
             var connectionU = new RepositoryBaseMongo("UserSkill");
             if (model.UserSkillId== 0)
             {
                 var statusList = connectionU.GetAll<UserSkill>().ToList();
                 int Id = 0;
                 if (statusList.Any())
                     Id = statusList.Max(x => x.UserSkillId);
                 Id += 1;
                 model.UserSkillId = Id;
                 model.UserId = userId;
                 connectionU.InsertOrUpdate(model);
             }

             else
             {
                 var result =
                     connectionU.GetAll<UserSkill>()
                         .FirstOrDefault(x => x.UserSkillId == model.UserSkillId);
                 result.Title = model.Title;
                
                 result.Description = model.Description;


                    model.UserId = userId;
             
                 connectionU.InsertOrUpdate(result);
             }
             //var userAcademy = new UserAcademyInfo();
            
              
             
             return RedirectToAction("UserProfileEdit");
         }

  

        [HttpPost]
         public ActionResult UserProfilePortfolioInfo(UserPortfolio model)
         {
             var connectionU = new RepositoryBaseMongo("UserPortfolio");

             var file = Request.Files[0];

             if (file != null && file.ContentLength > 0)
             {
                 var fileName = Path.GetFileName(file.FileName);
                 if (fileName != null)
                     model.ImageURl = Guid.NewGuid().ToString().Trim() +"."+ fileName.Split('.').LastOrDefault();
                 var path = Path.Combine(Server.MapPath("~/Content/UserProfile/UserPortfolio/"), model.ImageURl);
                 file.SaveAs(path);
             }
             if (model.UserPortfolioId== 0)
             {
                 var statusList = connectionU.GetAll<UserPortfolio>().ToList();
                 int Id = 0;
                 if (statusList.Any())
                     Id = statusList.Max(x => x.UserPortfolioId);
                 Id += 1;
                 model.UserPortfolioId = Id;
                 model.UserId = userId;
                 connectionU.InsertOrUpdate(model);
             }

             else
             {
                 var result =
                     connectionU.GetAll<UserPortfolio>()
                         .FirstOrDefault(x => x.UserPortfolioId == model.UserPortfolioId);
                 result.Title = model.Title;
                
                 result.Description = model.Description;


                 result.ImageURl = model.ImageURl;
            
                 connectionU.InsertOrUpdate(result);
             }
             //var userAcademy = new UserAcademyInfo();
            
              
             
             return RedirectToAction("UserProfileEdit");
         }
         [HttpPost]
         public ActionResult UserProfileCompanyInfo(UserCompanyInfo model)
         {
             var connectionU = new RepositoryBaseMongo("UserCompanyInfo");
             if (model.UserCompanyInfoId == 0)
             {
                 var statusList = connectionU.GetAll<UserCompanyInfo>().ToList();
                 int Id = 0;
                 if (statusList.Any())
                     Id = statusList.Max(x => x.UserCompanyInfoId);
                 Id += 1;
                 model.UserCompanyInfoId = Id;
                 model.UserId = userId;
                 connectionU.InsertOrUpdate(model);
             }

             else
             {
                 var result =
                     connectionU.GetAll<UserCompanyInfo>()
                         .FirstOrDefault(x => x.UserCompanyInfoId == model.UserCompanyInfoId);
                 result.CompanyDivision = model.CompanyDivision;
                 result.CompanyStartDate = model.CompanyStartDate;
                 result.CompanyEndDate = model.CompanyEndDate;
                 result.CompanyName = model.CompanyName;
                 result.Description = model.Description;


                    model.UserId = userId;
             
                 connectionU.InsertOrUpdate(result);
             }
             //var userAcademy = new UserAcademyInfo();
            
              
             
             return RedirectToAction("UserProfileEdit");
         }


         public JsonResult UserSkillEdit(int id)
        {
            var connectionU = new RepositoryBaseMongo("UserSkill");
            var company = connectionU.GetAll<UserSkill>().FirstOrDefault(x => x.UserSkillId == id);
            
         
            var view = RenderPartialViewToString("_partialSkillInfo", company);
            return Json(view, JsonRequestBehavior.AllowGet);


        }
         public JsonResult UserPortfolioEdit(int id)
        {
            var connectionU = new RepositoryBaseMongo("UserPortfolio");
            var company = connectionU.GetAll<UserPortfolio>().FirstOrDefault(x => x.UserPortfolioId == id);
            
         
            var view = RenderPartialViewToString("_partialPortfolioInfo", company);
            return Json(view, JsonRequestBehavior.AllowGet);


        }

        
        public JsonResult UserCompanyEdit(int id)
        {
             var connectionU = new RepositoryBaseMongo("UserCompanyInfo");
             var company = connectionU.GetAll<UserCompanyInfo>().FirstOrDefault(x=>x.UserCompanyInfoId==id);
             company.YearList = new List<int>();
             var currentYear = DateTime.UtcNow.Year;
             for (int i = DateTime.UtcNow.AddYears(-80).Year; i <= currentYear; i++)
             {
                 company.YearList.Add(i);
             }

            var view = RenderPartialViewToString("_partialCompanyInfo", company);
            return Json(view, JsonRequestBehavior.AllowGet);


        }
        public JsonResult UserAcademyEdit(int id)
        {
            var connectionU = new RepositoryBaseMongo("UserAcademyInfo");
            var company = connectionU.GetAll<UserAcademyInfo>().FirstOrDefault(x => x.UserAcademyInfoId == id);
             company.YearList = new List<int>();
             var currentYear = DateTime.UtcNow.Year;
             for (int i = DateTime.UtcNow.AddYears(-80).Year; i <= currentYear; i++)
             {
                 company.YearList.Add(i);
             }

             company.DegreeList = new SelectList(Enum.GetValues(typeof(DegreeEnum)).Cast<DegreeEnum>().Select(x => new SelectListItem()
             {
                 Text = (x).ToString(),
                 Value = ((int)x).ToString()
             }), "Value", "Text");


             company.CityList = new SelectList(Enum.GetValues(typeof(CityEnum)).Cast<CityEnum>().Select(x => new SelectListItem()
             {
                 Text = (x).ToString(),
                 Value = ((int)x).ToString()
             }), "Value", "Text");
             var conCon = new RepositoryBaseMongo("Country");
             company.CountryList = new SelectList(conCon.GetAll<Country>(), "CountryID", "Title");
             var conState = new RepositoryBaseMongo("State");
             company.StateList = new SelectList(conState.GetAll<State>(), "StateId", "Title");

            var view = RenderPartialViewToString("_partialAcademyInfo", company);
            return Json(view, JsonRequestBehavior.AllowGet);


        }

        
        [HttpPost]
        public ActionResult UserProfilePersonalDetail(UserProfileViewModel viewModel, List<int> socialSetting, List<int> Tvhabit)
        {
            var connectionU = new RepositoryBaseMongo("UserDetails");
            var conSocial = new RepositoryBaseMongo("UserSocialSetting");
            var conHabit = new RepositoryBaseMongo("UserTvHabit");
            var user = connectionU.GetAll<UserDetails>().FirstOrDefault(x => x.UserId == userId);
            if (user != null)
            {


                user.SexualOrientationId = viewModel.UserDetails.SexualOrientationId;
                user.EthnicityId = viewModel.UserDetails.EthnicityId;
                user.HeightId = viewModel.UserDetails.HeightId;
                user.WeightId = viewModel.UserDetails.WeightId;

                user.EyeColorId = viewModel.UserDetails.EyeColorId;
                user.Language = viewModel.UserDetails.Language;
                user.LivingId = viewModel.UserDetails.LivingId;
                user.ReligionId = viewModel.UserDetails.ReligionId;
                user.SmokingHabitId = viewModel.UserDetails.SmokingHabitId;
                user.DrinkingHabitId = viewModel.UserDetails.DrinkingHabitId;

                var userSocialList = conSocial.GetAll<UserSocialSetting>().Where(x => x.UserDetailsId == user.UserDetailsId).Select(x => x._id);
                if (userSocialList.Any())
                {
                    foreach (var item in userSocialList)
                    {
                        conSocial.Delete<UserSocialSetting>(item);
                    }
                }
                if (socialSetting.Any())
                {
                    foreach (var item in socialSetting)
                    {
                        var social = new UserSocialSetting();
                        social.SocialSettingId = item;
                        social.UserDetailsId = user.UserDetailsId;
                        conSocial.InsertOrUpdate(social);
                    }
                }
                var userhabitList = conHabit.GetAll<UserTvHabit>().Where(x => x.UserDetailsId == user.UserDetailsId).Select(x => x._id);
                if (userhabitList.Any())
                {
                    foreach (var item in userhabitList)
                    {
                        conHabit.Delete<UserTvHabit>(item);
                    }
                }
                if (Tvhabit.Any())
                {
                    foreach (var item in Tvhabit)
                    {
                        var social = new UserTvHabit();
                        social.IvHabitId = item;
                        social.UserDetailsId = user.UserDetailsId;
                        conHabit.InsertOrUpdate(social);
                    }
                }
                connectionU.InsertOrUpdate(user);
            }
            else
            {
                user = new UserDetails();
                var statusList = connectionU.GetAll<UserDetails>().ToList();
                int Id = 0;
                if (statusList.Any())
                    Id = statusList.Max(x => x.UserDetailsId);
                Id += 1;

                user.UserId = userId;
                user.UserDetailsId = Id;


                user.SexualOrientationId = viewModel.UserDetails.SexualOrientationId;
                user.EthnicityId = viewModel.UserDetails.EthnicityId;
                user.HeightId = viewModel.UserDetails.HeightId;
                user.WeightId = viewModel.UserDetails.WeightId;

                user.EyeColorId = viewModel.UserDetails.EyeColorId;
                user.Language = viewModel.UserDetails.Language;
                user.LivingId = viewModel.UserDetails.LivingId;
                user.ReligionId = viewModel.UserDetails.ReligionId;
                user.SmokingHabitId = viewModel.UserDetails.SmokingHabitId;
                user.DrinkingHabitId = viewModel.UserDetails.DrinkingHabitId;
                if (socialSetting.Any())
                {
                    foreach (var item in socialSetting)
                    {
                        var social = new UserSocialSetting();
                        social.SocialSettingId = item;
                        social.UserDetailsId = Id;
                        conSocial.InsertOrUpdate(social);
                    }
                }
                if (Tvhabit.Any())
                {
                    foreach (var item in Tvhabit)
                    {
                        var social = new UserTvHabit();
                        social.IvHabitId = item;
                        social.UserDetailsId = Id;
                        conHabit.InsertOrUpdate(social);
                    }
                }
                connectionU.InsertOrUpdate(user);


            }
            return RedirectToAction("UserProfileEdit");
        }
        public ActionResult UserFriendProfile(int friendId)
        {
            var connection = new RepositoryBaseMongo("Users");
            var connectionU = new RepositoryBaseMongo("UserDetails");
            var connectionF = new RepositoryBaseMongo("FriendList");
            var user = connection.GetAll<Users>().FirstOrDefault(x => x.UserId == friendId);
            var userDetails = connectionU.GetAll<UserDetails>().FirstOrDefault(x => x.UserId == friendId);
            var viewModel = new UserProfileViewModel();
            viewModel.Users = user;
            viewModel.UserDetails = userDetails;

            viewModel.UserFriendList = (from n in UtilityService.GetFriendList(friendId)
                                        join u in connection.GetAll<Users>().ToList() on n equals u.UserId
                                        select new User_Friend()
                                        {
                                            UserId = u.UserId,
                                            FullName = u.FirstName + " " + u.LastName,
                                            ImageUrl = u.ImageUrl
                                        }).ToList();


            return View(viewModel);
        }

        [HttpPost]
        public ActionResult UserProfileContact(UserProfileViewModel viewModel)
        {
            var connectionU = new RepositoryBaseMongo("UserDetails");
            var user = connectionU.GetAll<UserDetails>().FirstOrDefault(x => x.UserId == userId);
            if (user != null)
            {
                user.MobileNo = viewModel.UserDetails.MobileNo;
                user.Country = viewModel.UserDetails.Country;
                user.City = viewModel.UserDetails.City;
                user.Religion = viewModel.UserDetails.Religion;
            
                

                connectionU.InsertOrUpdate(user);
            }
            else
            {
                user= new UserDetails();
                var statusList = connectionU.GetAll<UserDetails>().ToList();
                int Id = 0;
                if (statusList.Any())
                    Id = statusList.Max(x => x.UserDetailsId);
                Id += 1;
                user.MobileNo = viewModel.UserDetails.MobileNo;
                user.Country = viewModel.UserDetails.Country;
                user.City = viewModel.UserDetails.City;
                user.Religion = viewModel.UserDetails.Religion;
                user.UserId = userId;
                user.UserDetailsId = Id;
                connectionU.InsertOrUpdate(user);
            }
            return RedirectToAction("UserProfileEdit");
        }

        [HttpPost]
        public ActionResult UserProfileAboutUs(UserProfileViewModel viewModel)
        {
            var connectionU = new RepositoryBaseMongo("UserDetails");
            var user = connectionU.GetAll<UserDetails>().FirstOrDefault(x => x.UserId == userId);
            if (user != null)
            {
                user.AboutYout = viewModel.UserDetails.AboutYout;
                connectionU.InsertOrUpdate(user);
            }
            else
            {
                user = new UserDetails();
                var statusList = connectionU.GetAll<UserDetails>().ToList();
                int Id = 0;
                if (statusList.Any())
                    Id = statusList.Max(x => x.UserDetailsId);
                Id += 1;
                user.AboutYout = viewModel.UserDetails.AboutYout;
                user.UserId = userId;
                user.UserDetailsId = Id;
                connectionU.InsertOrUpdate(user);
            }
            return RedirectToAction("UserProfileEdit");
        }
        [HttpPost]
        public ActionResult UserProfileFav(UserProfileViewModel viewModel)
        {
            var connectionU = new RepositoryBaseMongo("UserDetails");
            var user = connectionU.GetAll<UserDetails>().FirstOrDefault(x => x.UserId == userId);
            if (user != null)
            {
                user.FavQuotation = viewModel.UserDetails.FavQuotation;
               connectionU.InsertOrUpdate(user);
            }
            else
            {
                user = new UserDetails();
                var statusList = connectionU.GetAll<UserDetails>().ToList();
                int Id = 0;
                if (statusList.Any())
                    Id = statusList.Max(x => x.UserDetailsId);
                Id += 1;
                user.FavQuotation = viewModel.UserDetails.FavQuotation;
                user.UserId = userId;
                user.UserDetailsId = Id;
                connectionU.InsertOrUpdate(user);
            }
            return RedirectToAction("UserProfileEdit");
        }
        [HttpPost]
        public ActionResult UserProfileEdit(UserProfileViewModel model, string dob_month, string dob_day, string dob_year)
        {
          
            var connection = new RepositoryBaseMongo("Users");
            var user = connection.GetAll<Users>().FirstOrDefault(x => x.UserId == userId);
            user.FirstName = model.Users.FirstName;
            user.LastName = model.Users.LastName;
            var dob = dob_month + "/" + dob_day + "/" + dob_year;
            user.BirthDay = Convert.ToDateTime(dob).AddDays(1);
            user.Gender = model.Users.Gender;
            user.BhUsername = model.Users.BhUsername;
            var file = Request.Files[0];
           
            if (file != null && file.ContentLength > 0)
            {
                user.ImageUrl = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/UserProfile/User/"), user.ImageUrl);
                file.SaveAs(path);
            }
           connection.InsertOrUpdate(user);
            return RedirectToAction("Index");
        }
        [HttpPost]
        public ActionResult StreamData(string url)
        {
            var source = "share this";
            string titlenodeinnertext = "";
            if (Request.Params[0] == null)
            {
                return Content(null);
            }
            var longurl = Request.Params[0];
            if (!longurl.Contains("http://") && !longurl.Contains("https://"))
            {
                longurl = "http://" + longurl; //input url
            }
            var rgxUrl = new Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
            if (!rgxUrl.IsMatch(longurl))
            {
                return Content(null);
            }
            var data = new FeedSourceDetail();
            var htmlWeb = new HtmlWeb();
            var stringBuilder = new StringBuilder();
            try
            {
                var htmlDoc = htmlWeb.Load(longurl); //load url data
                if (htmlDoc.DocumentNode != null)
                {
                    var titleNode = htmlDoc.DocumentNode.SelectSingleNode("//title"); //select title
                    var desc = htmlDoc.DocumentNode.SelectSingleNode("//p"); //select desc
                    if (titleNode != null)
                    {
                        stringBuilder.Append("<a href='" + longurl + "' target='blank'>"); //prepare the link for display trim the title if length is >100
                        if (titleNode.InnerText.Count() > 100)
                        {
                            titlenodeinnertext = titleNode.InnerText.Substring(0, 100);
                            stringBuilder.Append(titlenodeinnertext + "</a>");
                        }
                        else
                        {
                            titlenodeinnertext = titleNode.InnerText;
                            stringBuilder.Append(titlenodeinnertext + "</a>");
                            //Sagar-Don't think it is necessary
                            //stringBuilder.Append("<p>" + url + "</p>");
                        }
                        if (desc != null) //adding some description text
                        {
                            if (desc.InnerText.Count() > 200)
                            {
                                stringBuilder.Append("<p>" + desc.InnerText.Substring(0, 200));
                                stringBuilder.Append("...");
                            }
                            else
                            {
                                stringBuilder.Append("<p>" + desc.InnerText + "</p>");
                            }
                        }

                        data.Body = stringBuilder.ToString();
                        data.Title = titlenodeinnertext;

                        // youtube image
                        int mInd = url.IndexOf("?v=");
                        if (mInd != -1)
                        {
                            string strVideoCode = url.Substring(url.IndexOf("?v=") + 3);
                            int ind = strVideoCode.IndexOf("?");
                            strVideoCode = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);
                            data.ImageUrl = "https://img.youtube.com/vi/" + strVideoCode + "/default.jpg";
                            data.Embed = url.Replace("watch?v=", "embed/");

                            // return "https://img.youtube.com/vi/" + strVideoCode + "/default.jpg";
                        }
                        ViewBag.Body = stringBuilder.ToString();
                        // Do something with title
                    }
                }
                else
                {
                    stringBuilder.Append("<a href='#'>");
                    stringBuilder.Append(longurl + "</a>");
                }
            }
            catch (Exception)
            {
                stringBuilder.Append("<a href='#'>");
                stringBuilder.Append(longurl + "</a>");
            }
            if (longurl.Length > 50)
            {
                ViewBag.Url = longurl;
                ViewBag.Title = titlenodeinnertext;
            }
            else
            {
                ViewBag.Url = longurl;
            }
            //return Content("true");

            var partialView = this.RenderPartialViewToString("_partialStreamData", data);
            return Json(new { view = partialView, body = data.Body, title = data.Title, image = data.ImageUrl, source = source, embed = data.Embed });
            // return Json(ViewBag.Body, JsonRequestBehavior.AllowGet);
        }
        public string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }
        public ActionResult Feed()
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            var list = new List<FeedPost>();
            var conC = new RepositoryBaseMongo("FeedandUserMapping");

            var category = conC.GetAll<FeedandUserMapping>().Where(x => x.UserID == userId).Select(x => x.CategoryId).ToList();
            if (category.Any())
            {
                list = connection.GetAll<FeedPost>().Where(x => category.Contains(x.CategoryId)).ToList();
                return View(list);
            }
            else
            {
                return RedirectToAction("AccountSetting");
            }


        }

        public ActionResult FriendPost()
        {
            var existingUser = ChatHelper.GetChatUserFromCookie(this.Request);
            if (existingUser != null)
            {
                if (!ChatHub.IsUserRegistered(existingUser))
                {
                    // cookie is invalid
                    ChatHelper.RemoveCookie(this.Response);
                    return this.RedirectToAction("FriendPost");
                }
            }
            var connection = new RepositoryBaseMongo("Status");
            var data = connection.GetAll<Status>().Where(x => !x.IsDeleted).OrderByDescending(x => x.CreatedDate);
            var viewModel = new ProfileIndexViewModel();
            viewModel.Statuses = data;
            viewModel.ChatModel = null;
            viewModel.PostType = "1";
            var user = new ChatUser()
            {
                Name = WebSecurity.CurrentUserName,
                Email = WebSecurity.CurrentUserName,
                ProfilePictureUrl = WebSecurity.CurrentUserName,
                Id = new Random().Next(100000),
                Status = ChatUser.StatusType.Online,
                RoomId = ChatController.ROOM_ID_STUB
            };

            // for signalr
            {
                ChatHub.RegisterNewUser(user);
            }

            // for long-polling
            {
                ChatServer.SetupRoomIfNonexisting(ChatController.ROOM_ID_STUB);
                ChatServer.Rooms[ChatController.ROOM_ID_STUB].RegisterNewUser(user);
            }
            ChatHelper.CreateNewUserCookie(this.Response, user);
            // in this case the authentication cookie is valid and we must render the chat
            viewModel.ChatModel = new ChatViewModel()
            {
                IsUserAuthenticated = true,
                UserId = userId,
                UserName = WebSecurity.CurrentUserName,
                UserProfilePictureUrl = WebSecurity.CurrentUserName
            };

            viewModel.PostType = "2";
            return View(viewModel);
        }

        public ActionResult MyUrl()
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            var data = connection.GetAll<FeedPost>().Where(x => x.IsActive && x.PostByUserId== userId && x.PostType=="submit");
            return View( data);
        }

        public ActionResult MyStories()
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            var data = connection.GetAll<FeedPost>().Where(x => x.IsActive && x.PostByUserId== userId && x.PostType=="submitUrl");
            return View("MyUrl", data);
        }



        public JsonResult CheckBhUserName(string BhUsername)
        {
            var connection = new RepositoryBaseMongo("Users");
            var currentuser = connection.Find<Users>(userId).BhUsername;
            var user = false;
            if (BhUsername != currentuser)
            {
               user = connection.GetAll<Users>().Any(x =>  x.BhUsername == BhUsername);
               // return user ? Json(true, JsonRequestBehavior.AllowGet) : Json("Already Exists", JsonRequestBehavior.AllowGet);
            }

            return user ? Json("true", JsonRequestBehavior.AllowGet) : Json("fasle", JsonRequestBehavior.AllowGet);
        }


        #region Account Setting

        public ActionResult AccountSetting()
        {
            var connection = new RepositoryBaseMongo("Category");
                var list = connection.GetAll<Category>().ToList();
            var selected = new List<string>();
                var conFU = new RepositoryBaseMongo("FeedandUserMapping");
            var feedlist = conFU.GetAll<FeedandUserMapping>().ToList();
            if (feedlist.Any())
            {
                selected = feedlist.Where(x => x.UserID == userId).Select(x => x.CategoryId.ToString()).ToList();
                
            }

            ViewBag.Selected = selected;

            ViewBag.CategoryList = new SelectList(list, "CategoryId", "ShortDescription", selected);
            return View();
        }
        [HttpPost]
        public ActionResult AccountSetting(List<int> category )
        {
            var connection = new RepositoryBaseMongo("Category");
            var list = connection.GetAll<Category>().ToList();
            var conFU = new RepositoryBaseMongo("FeedandUserMapping");
            if (category.Any())
            {
                foreach (var item in category)
                {
                     var data = new FeedandUserMapping();
                    data.UserID = userId;
                    data.CategoryId = item;
                    conFU.InsertOrUpdate(data);
                }
               
            }

            var selected = new List<string>();
            var feedlist = conFU.GetAll<FeedandUserMapping>().ToList();
            if (feedlist.Any())
            {
                selected = feedlist.Where(x => x.UserID == userId).Select(x => x.CategoryId.ToString()).ToList();

            }

            ViewBag.Selected = selected;

            ViewBag.CategoryList = new SelectList(list, "CategoryId", "ShortDescription");
            return View();
        }

        
        #endregion
    }
}
